package com.weme.matching


import android.content.Context
import android.graphics.Rect
import android.os.Handler
import android.os.Looper
import android.util.DisplayMetrics
import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.ProcessLifecycleOwner
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.LinearSmoothScroller
import androidx.recyclerview.widget.PagerSnapHelper
import androidx.recyclerview.widget.RecyclerView
import com.alibaba.android.arouter.facade.annotation.Route
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.QuickViewHolder
import com.gyf.immersionbar.BarHide
import com.gyf.immersionbar.ImmersionBar
import com.hjq.permissions.Permission
import com.hjq.permissions.XXPermissions
import com.jeremyliao.liveeventbus.LiveEventBus
import com.makeramen.roundedimageview.RoundedImageView
import com.osom.proto.message.Brocast
import com.weme.common.arouter.ARouterHelper
import com.weme.common.arouter.ARouterPaths
import com.weme.common.base.BaseFragment
import com.weme.common.dialog.PermissingDialog
import com.weme.common.dialog.RechargeDialog
import com.weme.common.dialog.RechargeDialogCallback
import com.weme.common.manager.SocketConnectManager
import com.weme.common.network.MATCH_HALL_TIPS
import com.weme.common.util.*
import com.weme.matching.activity.MatchingActivity
import com.weme.matching.databinding.FragmentMatchingBinding
import com.weme.matching.viewmode.MatchingViewMode
import dev.kratos.api.im_server.v1.GetMatchBannerReply
import dev.kratos.api.im_server.v1.MatchReply
import dev.kratos.api.user_server.v1.GetAccountInfoReply
import dev.kratos.api.user_server.v1.GiftInfo


class GalleryItemDecoration(private val spacing: Int) : RecyclerView.ItemDecoration() {
    override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State) {
        val position = parent.getChildAdapterPosition(view)
        if (position != RecyclerView.NO_POSITION) {
            outRect.left = spacing
            outRect.right = spacing
        }
    }
}

@Route(path = ARouterPaths.MATCHINGFRAGMENT)
class MatchingFragment : BaseFragment<FragmentMatchingBinding, MatchingViewMode>() {
    var matchList = mutableListOf<String>()
    private var layoutManager: LinearLayoutManager? = null
    private val autoScrollHandler = Handler(Looper.getMainLooper())
    private var currentPage = 4 //默认到第四个 不然会翻页会有问题
    private var pairCards = 0L //匹配卡
    private var vipLevel = 0 //VIp等级
    private var coins = 0L //金币
    private var matchUseNum = 0 //匹配金额
    var page = 1

    // val adapter = MyPagerAdapter()

    private val autoScrollRunnable: Runnable = object : Runnable {
        override fun run() { //  Log.e("tag","1111111111111111111111111、、、、、"+currentPage)
            val smoothScroller: RecyclerView.SmoothScroller = object : LinearSmoothScroller(requireActivity()) {
                override fun calculateSpeedPerPixel(displayMetrics: DisplayMetrics?): Float {
                    return 100f / displayMetrics!!.densityDpi
                }
            }
            smoothScroller.targetPosition = ++currentPage
            layoutManager?.startSmoothScroll(smoothScroller)

            autoScrollHandler.postDelayed(this, 1000)
        }
    }

    override fun startOperate() { //        mBinding.svgaVip.playSVGAFromAssets(requireContext(), "become_vip.svga")
        ImmersionBar.with(this).hideBar(BarHide.FLAG_HIDE_NAVIGATION_BAR).titleBar(mBinding.calView).init()
        RtcEngineSingleton.getRtcEngine()
        mBinding.svgaCall.playSVGAFromAssets( "accept_bg")

        mBinding.tvTip.text = AppMkHelper.decodeString(MATCH_HALL_TIPS)
        SocketConnectManager.accountLiveData.observe(this) {
            mBinding.tvBalance.text = it.coins.toString()
        }

        SocketConnectManager.matchLiveData.observe(ProcessLifecycleOwner.get()) {
            startMatchingActivity()
        }

     LiveEventBus.get<Any>(LiveConfig.NET_WORK_MATCHING).observe(this) {

            if (it is GetMatchBannerReply) {
                mBinding.tvNum.text = it.matchPeople.toString()
                matchUseNum = it.matchUseNum
                matchList = it.matchBannerList
                initViewPger2()
                matchingAdapter.submitList(it.matchBannerList)
            } else if (it is MatchReply) {


                //     CallActivity.openActivity(requireActivity(), CallOperationType.INCOMING_MATCH,"")


            }
        }

     LiveEventBus.get<Any>(LiveConfig.NET_WORK_MATCH_NUMBER).observe(this) {
            if (it is Brocast.MatchCount) {
                mBinding.tvNum.text = it.count.toString()
            }
        }

        viewModel.getMatchBanner(page)
    }

    fun initAccount(it: GetAccountInfoReply) {
        mBinding.tvBalance.text = it.account.coins.toString() //一共有四种情况：1）未订阅没有匹配卡，则不显示价格和free；
        mBinding.imLabel.setVisible(it.account.pairCards > 0L)
   //     mBinding.imSpecies.setVisible(it.vipLevel > 0)
     //   mBinding.scvBalance.setVisible(it.vipLevel > 0)
        pairCards = it.account.pairCards
        coins = it.account.coins
        vipLevel = it.vipLevel


    }

    private fun startMatchingActivity() {
        val isDenied = mutableListOf(Permission.RECORD_AUDIO, Permission.CAMERA, Permission.WRITE_EXTERNAL_STORAGE).all { XXPermissions.isGranted(requireActivity(), it) }
        if (isDenied) {
            MatchingActivity.openActivity(requireActivity(), matchList, matchUseNum)

        } else {
            val permissingDialog = PermissingDialog(requireActivity(), mutableListOf<String>(Permission.RECORD_AUDIO, Permission.CAMERA, Permission.WRITE_EXTERNAL_STORAGE)) {
                MatchingActivity.openActivity(requireActivity(), matchList, matchUseNum)
            }
            permissingDialog.show(requireActivity().supportFragmentManager, "")
        }
    }


    private fun initViewPger2() {
        mBinding.recyclerView.let {
            this.layoutManager = LinearLayoutManager(requireActivity(), LinearLayoutManager.HORIZONTAL, false)
            it.layoutManager = layoutManager
            it.adapter = matchingAdapter
            it.setOnTouchListener { _, _ -> // 拦截触摸事件，返回 true 阻止滑动
                true
            }
        }
        val dia = -resources.getDimension(com.example.resources.R.dimen.dp_24)
        mBinding.recyclerView.addItemDecoration(GalleryItemDecoration(spacing = dia.toInt()))

        PagerSnapHelper().attachToRecyclerView(mBinding.recyclerView) //设置居中回弹

        mBinding.recyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)
                val layoutManager = recyclerView.layoutManager
                if (layoutManager is LinearLayoutManager) {
                    val firstVisibleItemPosition = layoutManager.findFirstVisibleItemPosition()
                  //  Log.e("tag",firstVisibleItemPosition.toString()+"//"+matchList.size)
                    if(matchList.size>10&&firstVisibleItemPosition>matchList.size-5){
                        page += 1
                      //  viewModel.getMatchBanner(page)
                    }

                }
                val centerPoint = recyclerView.width / 2f
                val totalChildCount = recyclerView.childCount
                for (i in 0 until totalChildCount) {
                    val child = recyclerView.getChildAt(i)
                    val childCenter = (child.left + child.right) / 2f
                    val childOffset = Math.abs(centerPoint - childCenter) / centerPoint

                    // 根据子视图距离中心的偏移量来动态计算缩放比例和层级
                    val scale = 1f - 0.3f * childOffset.coerceIn(0f, 1f)
                    child.scaleX = scale
                    child.scaleY = scale

                    // 通过比例来设置视图的层级
                    // 中间视图有最大的层级，两侧视图层级逐渐降低
                    child.translationZ = scale
                }
            }

        })
    }

    private val matchingAdapter = object : BaseQuickAdapter<String, QuickViewHolder>() {
        override fun onBindViewHolder(holder: QuickViewHolder, position: Int, item: String?) {
            if(matchList.isEmpty()){
                return
            }
            val realPosition = position % matchList.size //   holder.getView<ConstraintLayout>(R.id.calView).z = 0.1f

            matchList[realPosition].apply {
                val roundImg = holder.getView<RoundedImageView>(R.id.roundImg)
                roundImg.loadImage(this) //                Glide.with(roundImg)
                //                    .asBitmap()
                //                    .load(this)
                //                    .error(com.example.resources.R.mipmap.icon_head_null)
                //                    .apply(RequestOptions().centerCrop())
                //                    .into(object : CustomViewTarget<View, Bitmap>(roundImg) {
                //                        override fun onLoadFailed(errorDrawable: Drawable?) {
                //                            //    roundImg.loadImage(this@apply)
                //                        }
                //
                //                        override fun onResourceCleared(placeholder: Drawable?) {
                //
                //                        }
                //
                //                        override fun onResourceReady(resource: Bitmap, transition: Transition<in Bitmap>?) {
                //                            roundImg.setShaderBitmap(resource)
                //                        }
                //
                //                    })
            }
        }

        override fun getItemCount(items: List<String>): Int {
            return Int.MAX_VALUE
        }

        override fun onCreateViewHolder(context: Context, parent: ViewGroup, viewType: Int): QuickViewHolder {
            return QuickViewHolder(R.layout.item_matching, parent)
        }
    }

    override fun onResume() {
        super.onResume()
        autoScrollHandler.removeCallbacks(autoScrollRunnable)
        autoScrollHandler.postDelayed(autoScrollRunnable, 1000)
    }

    override fun onStart() {
        super.onStart()



    }

    override fun onStop() {
        super.onStop()

    }

    override fun clickListener() {
        mBinding.imSpecies.setOnFastClickListener {
            ARouterHelper.navigateToActivity(requireContext(), ARouterPaths.MINE_COINS_ACTIVITY)
        }
        mBinding.scvBalance.setOnFastClickListener {
            ARouterHelper.navigateToActivity(requireContext(), ARouterPaths.MINE_COINS_ACTIVITY)
        }
        mBinding.vTapMatch.setOnFastClickListener {
            if (requireContext().isNetworkAvailable()) {
                val isDenied = mutableListOf<String>(Permission.RECORD_AUDIO, Permission.CAMERA, Permission.WRITE_EXTERNAL_STORAGE).all { XXPermissions.isGranted(requireActivity(), it) }
                if (isDenied) {
                    startMatching()

                } else {
                    val permissingDialog = PermissingDialog(requireActivity(), mutableListOf<String>(Permission.RECORD_AUDIO, Permission.CAMERA, Permission.WRITE_EXTERNAL_STORAGE)) {
                        startMatching()
                    }
                    permissingDialog.show(requireActivity().supportFragmentManager, "")
                }

            } else {
                showToast(resources.getString(com.example.resources.R.string.null_network))
            }

        }

    }

    //匹配卡等服务端做完
    private fun startMatching() {
        if (pairCards > 0L) {
            showToast("匹配卡 = $pairCards")
            startMatchingActivity()
        } else {
            if (vipLevel > 0) {
                showToast("当前金币" + coins + "大于" + matchUseNum)
                if (coins >= matchUseNum) {
                    startMatchingActivity()
                } else {
                    GlobalLoadingDialog.dismiss()

//                    RechargeDialog.show(requireActivity(), object : RechargeDialogCallback {
//                        override fun sendGiftInfo(giftInfo: GiftInfo) {
//
//                        }
//
//                    })

                }

            } else { //未定义调整订阅商城

                GlobalLoadingDialog.dismiss()
                showToast("跳转到订阅商城")
            }
        }
    }


    override fun onPause() {
        super.onPause() // 在 onPause 中停止自动翻页
        autoScrollHandler.removeCallbacks(autoScrollRunnable)
        GlobalLoadingDialog.dismiss()
    }

    override fun getViewModel(): Class<MatchingViewMode> = MatchingViewMode::class.java
}
